package com.ygqh.baby.controller.admin;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.model.wdt.qyb.WdtQybResult;
import com.ygqh.baby.po.AdminContractArrive;
import com.ygqh.baby.po.AdminContractDetail;
import com.ygqh.baby.po.AdminPurchase;
import com.ygqh.baby.po.AdminPurchaseDetail;
import com.ygqh.baby.service.AdminContractDetailService;
import com.ygqh.baby.service.AdminPurchaseService;
import com.ygqh.baby.service.AdminSettlementService;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.task.WdtService;
import com.ygqh.baby.service.wdtqyb.api.WdtQybApi;
import com.ygqh.baby.service.wdtqyb.exception.WdtException;
import com.ygqh.baby.utils.JsonUtils;
import com.ygqh.baby.utils.MailUtil;

@Controller
@RequestMapping("/admin/purchase")
public class PurchaseController extends BaseController<Object, java.lang.Long> {

	@Autowired
	private AdminPurchaseService adminPurchaseService;
	@Autowired
	private AdminContractDetailService adminContractDetailService;
	@Autowired
	private AdminSettlementService adminSettlementService;
	@Autowired
	private WdtService wdtService;
	@Autowired
	private WdtQybApi wdtQybApi;
	@Autowired
	private MailUtil mailUtil;
	@Value("${mail.to}")
	private String SEND_TO;
	@Autowired
	private FileService fileService;

	@RequestMapping("syncPurchase")
	@ResponseBody
	public Message syncPurchase(String purchaseCode) {
		AdminPurchase purchase = adminPurchaseService.findPurchaseByCode(purchaseCode);
		if (StringUtil.isBlank(purchase.getWdtPurchaseCode())) {
			// WdtResult result = wdtService.createStockInOrder(purchase);
			WdtQybResult result;
			try {
				result = wdtQybApi.purchasePush(purchase);
				adminPurchaseService.writeBackWdtPurchaseCode(purchase.getPurchaseCode(), result.getMessage());
				return Message.success("同步成功");
			} catch (WdtException e) {
				e.printStackTrace();
				return Message.error(e.getMessage(), null);
			}

		}
		return Message.success("请不要重复同步");

	}

	@RequestMapping("searchPurchase")
	@ResponseBody
	public Map<String, Object> searchPurchase(String q, QueryInfo queryInfo, Date startDate, Date endDate, String purchaseCode,String contractCode) {

		ResultSet<AdminPurchase> resultSet = adminPurchaseService.search(queryInfo, q, startDate, endDate, purchaseCode,contractCode);

		return resultSet.toDatatables(null);
	}

	@RequestMapping("searchPurchaseList")
	@ResponseBody
	public List<AdminPurchase> searchPurchaseList(String q, QueryInfo queryInfo) {

		return adminPurchaseService.find();
	}

	@RequestMapping("savePurchase")
	@ResponseBody
	public Message savePurchase(String purchase) {
		AdminPurchase adminPurchase = JsonUtils.toObject(purchase, AdminPurchase.class);

		if (adminPurchase.getId() != null) {
			adminPurchase.setUpdateBy(getSession().getTrueName());
			adminPurchase.setUpdateTime(new Date());

			// 判断是否已经录入结算
			if (adminSettlementService.findByPurchaseCode(adminPurchase.getPurchaseCode()) > 0)
				return Message.error("进货单已经有结算单，无法修改");
		} else {
			adminPurchase.setCreateBy(getSession().getTrueName());
			adminPurchase.setCreateTime(new Date());
		}

		return adminPurchaseService.saveOrUpdate(adminPurchase) == 1 ? SUCCESS_MESSAGE : ERROR_MESSAGE;

	}

	@RequestMapping("getPurchaseById")
	@ResponseBody
	public Map<String, Object> getPurchaseById(String code) {
		AdminPurchase purchase = adminPurchaseService.findPurchaseByCode(code);
		List<AdminPurchase> list = new ArrayList<AdminPurchase>();
		list.add(purchase);
		ResultSet<AdminPurchase> resultSet = new ResultSet<AdminPurchase>(1, list);
		return resultSet.toDatatables(null);
	}

	@RequestMapping("getPurchaseDetailBySku")
	@ResponseBody
	public List<Map<String, Object>> getPurchaseDetailBySku(String skuCode, String contractCode) {
		return adminPurchaseService.selectPruchaseDetailBySku(skuCode, contractCode);
	}

	@RequestMapping("searchPurchaseReport")
	@ResponseBody
	public Map<String, Object> searchPurchaseReport(String skuCode, String supplierName, String contractCode, QueryInfo queryInfo, Date startDate, Date endDate) {

		ResultSet<AdminContractArrive> resultSet = adminPurchaseService
				.searchContractArrive(queryInfo, skuCode, supplierName, contractCode, startDate, endDate);

		return resultSet.toDatatables(null);
	}

	@RequestMapping("getPurchaseList")
	@ResponseBody
	public List<AdminPurchase> getPurchaseList(String contractCode) {

		return adminPurchaseService.selectPurchaseByContractCode(contractCode);

	}

	@RequestMapping("readTemplate")
	@ResponseBody
	public Message readTemplate(@RequestParam("uploadFile") MultipartFile uploadFile, Long contractId, HttpServletRequest request, HttpServletResponse respons)
			throws IOException {

		InputStream is = uploadFile.getInputStream();
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

		Map map = new HashMap();
		List<AdminPurchaseDetail> purchaseDetails = new ArrayList<>();
		List<String> skuCodeList = new ArrayList<>();
		try {
			// Read the Sheet
			for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
				if (xssfSheet == null) {
					continue;
				}
				// Read the Row
				for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
					XSSFRow xssfRow = xssfSheet.getRow(rowNum);
					if (xssfRow != null) {
						AdminPurchaseDetail model = new AdminPurchaseDetail();
						XSSFCell skuCode = xssfRow.getCell(0);
						XSSFCell quantity = xssfRow.getCell(4);
						model.setSkuCode(getValue(skuCode));
						if (quantity != null) {
							model.setQuantity(new BigDecimal(getValue(quantity).toString()));
						}

						checkData(model);
						String r = model.getRemark();
						if (model.getSkuCode() == null) {
							model.setRemark("SKU不能为空");
						} else {

							if (skuCodeList.contains(model.getSkuCode())) {
								model.setRemark(model.getRemark() + "sku重复;");
							} else {
								skuCodeList.add(model.getSkuCode());
								AdminContractDetail contractDetail = adminContractDetailService.findBySku(model.getSkuCode(), contractId);
								if (contractDetail == null) {
									model.setRemark(r + "SKU不存在;");
								} else {
									model.setProductName(contractDetail.getProductName());
									model.setSizeName(contractDetail.getSizeName());
									model.setPrice(contractDetail.getPrice());
									model.setColor(contractDetail.getColor());

								}
							}
						}
						purchaseDetails.add(model);

					}
				}
			}
			return Message.success(purchaseDetails);
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error(purchaseDetails);
		}

	}

	private void checkData(AdminPurchaseDetail model) {
		StringBuilder remark = new StringBuilder();
		if (model.getSkuCode() == null) {
			remark.append("SKU不能为空;");
		}

		if (model.getQuantity() == null || model.getQuantity().intValue() <= 0) {
			remark.append("请填写进货数量;");
		}
		model.setRemark(remark.toString());
	}

	/**
	 * 得到Excel表中的值
	 *
	 * @param hssfCell
	 *            Excel中的每一个格子
	 * @return Excel中每一个格子中的值
	 */
	@SuppressWarnings("static-access")
	private String getValue(XSSFCell hssfCell) {
		if (hssfCell == null)
			return null;
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			DecimalFormat df = new DecimalFormat("0");
			String str = df.format(hssfCell.getNumericCellValue());
			// 返回数值类型的值
			return str;
		} else {
			// 返回字符串类型的值
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}

	@RequestMapping("updateLogic")
	@ResponseBody
	public Message updateLogic(String purchaseCode, String logisticsCode, String expressCompany, Date arriveDate, String remark) throws Exception {
		AdminPurchase purchase = new AdminPurchase();
		purchase.setPurchaseCode(purchaseCode);
		purchase.setPreArriveDate(arriveDate);
		purchase.setLogisticsCode(logisticsCode);
		purchase.setExpressCompany(expressCompany);
		purchase.setRemark(remark);
		adminPurchaseService.updateLogicCode(purchase);
		purchase = adminPurchaseService.findPurchaseByCode(purchaseCode);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		StringBuffer str = new StringBuffer();
		str.append("<html><head><style>.table-d table{ background:#000;font-size:14px} .table-d table td{ background:#FFF} h5{width: auto;margin-right: 20px} .title{display: flex;line-height: 10px}");
		str.append("</style></head><body><div class='title'><h5>进货单号：" + purchase.getPurchaseCode() + "</h5>");
		str.append("<h5>旺店通单号：" + purchase.getWdtPurchaseCode() + "</h5>");
		str.append("<h5>物流公司：" + purchase.getExpressCompany() + "</h5>");
		str.append("<h5>物流单号：" + purchase.getLogisticsCode() + "</h5>");
		str.append("</div><div class='title'>");
		str.append("<h5>进货单件数：" + purchase.getArriveAmount() + "</h5>");
		str.append("<h5>预计到货时间：" + formatter.format(purchase.getPreArriveDate()) + "</h5>");
		str.append("<h5>备注：" + remark + "</h5>");
		str.append("</div><div class='table-d'>");
		str.append("<table width='800' border='0' cellspacing='1' cellpadding='0'><tr><td width='15%'>商品编码</td><td width='40%'>商品名称</td><td width='10%'>颜色</td><td width='15%'>尺码</td><td width='10%'>数量</td></tr>");

		for (AdminPurchaseDetail detail : purchase.getPurchaseDetail()) {
			str.append("<tr><td>" + detail.getSkuCode() + "</td>");
			str.append("<td>" + detail.getProductName() + "</td>");
			str.append("<td>" + detail.getColor() + "</td>");
			str.append("<td>" + detail.getSizeName() + "</td>");
			str.append("<td>" + detail.getQuantity() + "</td>");
			str.append("</tr>");
		}
		str.append("</table><div></body></html>");

		mailUtil.sendWithHtml(SEND_TO.split(";"), "进货单【" + purchaseCode + "】发货通知", str.toString());
		return SUCCESS_MESSAGE;

	}
	@RequestMapping("exportPurchaseReport")
	
	public void exportPurchaseReport(String skuCode, String supplierName, String contractCode,HttpServletRequest request,HttpServletResponse response) {
		QueryInfo queryInfo=new QueryInfo();
		queryInfo.setEnd(200000);
		
		List<AdminContractArrive> list = adminPurchaseService
				.selectContractArrive(queryInfo, skuCode, supplierName, contractCode, null, null);
		byte[] bytes = fileService.downloadFromOss("template/purchase_report.xlsx"); 
		List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
		Map<String, Object> dataMap = new HashMap<String, Object>();

		dataMap.put("resultSet", list);
		dataMaps.add(dataMap);
		DocumentHandler.DownloadExcel(bytes, "入库统计.xlsx", dataMap, request, response);
		
	}
	@RequestMapping("exportPurchase")
	public void exportPurchase(String q, String purchaseCode,HttpServletRequest request,HttpServletResponse response){
	
		//查询入库数据
		List<AdminPurchase> resultSet = adminPurchaseService.searchPurchase(q, purchaseCode);
		
		
		byte[] bytes = fileService.downloadFromOss("template/purchase_instock.xlsx"); 
		List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("resultSet", resultSet);
		dataMaps.add(dataMap);
		DocumentHandler.DownloadExcel(bytes, "入库统计.xlsx", dataMap, request, response);
		
	}
	@RequestMapping("deletePurchase")
	@ResponseBody
	public Message deletePurchase(Long id){		
		
		adminPurchaseService.deleteSoft(id);
		
	return SUCCESS_MESSAGE;
	}
	
}
